package com.quan.sdk.weixin.tools;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mzlion.easyokhttp.HttpClient;
import com.quan.common.utils.EncryptPropertyConfigurer;
import com.quan.sdk.weixin.common.WeixinContext;
import com.quan.sdk.weixin.model.AccessToken;

/**
 * AccessToken全局唯一接口调用凭据工具类
 * @author yhaoquan
 *
 */
public class AccessTokenTools {
	
	private static Logger logger = LoggerFactory.getLogger(AccessTokenTools.class);
	
	/**
	 * Access_Token 公众号的全局唯一接口调用凭据
	 * <br>方式：GET
	 * <br>参数：
	 * <br>&nbsp;&nbsp;&nbsp; appid
	 * <br>&nbsp;&nbsp;&nbsp; secret
	 */
	public static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" ;

	/**
	 * 获取AccessToken
	 * @param appid
	 * @param secret
	 * @return
	 */
	public static AccessToken getAccessToken(String appid, String secret) {
		if(StringUtils.isEmpty(appid)) {
			appid = EncryptPropertyConfigurer.getValue("APPID");
		}
		if(StringUtils.isEmpty(secret)) {
			secret = EncryptPropertyConfigurer.getValue("APPSECRET");
		}
		String token = EncryptPropertyConfigurer.getValue("TOKEN");
		if(StringUtils.isEmpty(token)) {
			logger.info("无法获取微信Token");
			return null;
		}
		
		if(StringUtils.isEmpty(appid)) {
			logger.info("无法获取APPID");
			return null;
		}
		if(StringUtils.isEmpty(secret)) {
			logger.info("无法获取APPSECRET");
			return null;
		}
		
		WeixinContext.setAPPID(appid);
		WeixinContext.setSECRET(secret);
		WeixinContext.setTOKEN(token);
		
		String url = String.format(ACCESS_TOKEN_URL, appid, secret) ;
		
		AccessToken accessToken = HttpClient.get(url).execute().asBean(AccessToken.class) ;
		if(null != accessToken) {
			if (accessToken.getErrcode() == 0) {
				logger.info("AccessToken【{}】", accessToken.getAccess_token());
				//保存到全局缓存中，方便接口调用
				WeixinContext.setAccessToken(accessToken.getAccess_token());
			} else {
				logger.info("AccessToken获取失败，错误原因：{}", accessToken.getErrmsg());
			}
		} else {
			logger.info("AccessToken获取失败，请检查API地址是否正确：{}", url);
		}
		
		return accessToken ;
	}
	
	public static AccessToken getAccessToken() {
		return getAccessToken(null, null) ;
	}
	
}
